function getCookie(name){
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    try {
        return (arr = document.cookie.match(reg)) ? decodeURIComponent(arr[2]) : null;
    } 
    catch (e) {
        return null;
    }
}  
function setCookie(name, value, expire, domain){
    function _setCookie(name, value, expire, domain){
        var exp = new Date();
        exp.setTime(exp.getTime() + expire);
        var str = name + "=" + encodeURIComponent(value) + ";expires=" + exp.toGMTString() + ";path=/;";
        if (domain && domain != 'localhost') {
            str += "domain=" + domain;
        }
        document.cookie = str;
    }
	var exp = (typeof expire == "number") ? expire : 365 * 24 * 60 * 60 * 1000;
    _setCookie(name, value, exp, domain);
}
	
var _m = chrome.i18n.getMessage, userInfo, guard={
	docReady:false,
	userRun:false,
	userViewMode:null,
	refreshImgCountHandle:null,
	refreshImgCount:0,
	refreshImgMaxCount:15,
	refreshImgCountInterval:400,
	petEntity:null,
	ready:function(){
		this.docReady = true;
		if (this.userRun){
			this.run();
		}
	},
	run:function(viewMode){
		viewMode = viewMode || this.userViewMode;
		happyReader.main(viewMode);
		this.clearRefreshImgHandle();
	},
	showTip:function(){
		var tip = $.createEle('div', {className:''}, {cssText:'z-index:999999;position:absolute;top:40%;left:40%;padding:5px 40px;line-height:60px;font-size:25px;color:#fff;text-align:center;opacity:1;background:rgba(0,0,0,.65);border-radius:6px;-webkit-transition: all .6s linear;'})
		  .html(_m('guardTip'))
		  .appendTo($('body'));
		  
		setTimeout(function(){
		   tip.css({opacity:0});
		   setTimeout(function(){$.removeEle(tip);}, 600);
		}, 600);
	},
	clearRefreshImgHandle:function(){
		clearTimeout(this.refreshImgCountHandle);
        this.refreshImgCountHandle = null;
	},
	refreshImg:function(){
		guard.refreshImgCountHandle = setTimeout(function(){
			if (guard.refreshImgCount++ <= guard.refreshImgMaxCount) {
				guard.refreshImgCountInterval = 1.5*guard.refreshImgCountInterval|0;
				happyReader.getImgData();
				if (happyReaderImg.checkModeValid()){
				    guard.petEntity ? $('#happyReaderImgTab').attr({className:'enable', onclick:function(){guard.clickPetTabAnimate(this, 'img')}}) : guard.createPet();
				    happyReaderImg.imgData.big.length && $('#happyReaderImgCount').html(happyReaderImg.imgData.big.length);
				}
				guard.refreshImg();
			}else{
				guard.clearRefreshImgHandle();
			}
		}, guard.refreshImgCountInterval);
	},
	clickPetTabAnimate:function(self, type){
		type = type.toLowerCase();
		$(self).css({opacity:0,webkitTransform:'scale(2.5)'});
		setTimeout(function(){guard.run(type)},500);
		_gaq.push(['_trackEvent', 'callExtMode::pet', 'callExtMode', 'pet:'+type]);
	},
	createPet:function(){
		$.loadfile({
		  'type':'css', 
		  'url':chrome.extension.getURL('css/happyReaderPet.css')
		});
		
		this.petEntity = $.createEle(
		  'div', 
		  {id:'happyReaderPet'}
		)
		.html('<img src="'+chrome.extension.getURL('img/icon-48.png')+'" width=32 height=32/><b id="happyReaderImgCount"></b><a id="happyReaderImgTab">'+_m("picture")+'</a><a id="happyReaderTextTab">'+_m("text")+'</a>')
		.appendTo($('body'));
		
		['Img', 'Text'].forEach(function(item){
			window['happyReader'+item].checkModeValid() && $('#happyReader'+item+'Tab').attr({className:'enable', onclick:function(){guard.clickPetTabAnimate(this, item)}});
		});
		
	   _gaq.push(['_trackEvent', 'createPet', 'createPet']);
	}
}

var options_hotkey, 
    isTabForNextPage = false, 
	setting_textSkin = false,
	options_enableAnalysisHelper = false, 
	options_enableSuperAutoNextPage = false, 
	connection = chrome.extension.connect();

if (!userInfo){
	connection.postMessage({"action":"getUserInfo"});
    connection.onMessage.addListener(function(msg, conn){
		userInfo = msg.userInfo;
		if (userInfo && location.hostname == 'os.heimali.com') {
			setCookie("token", userInfo.token);
			setCookie("uid", userInfo.uid);
			setCookie("name", userInfo.name);
		}
    });
}

connection.postMessage({"action":"isTabForNextPage"});
connection.onMessage.addListener(function(msg,conn){
	if (msg.isTabForNextPage){
		isTabForNextPage = true;
		$('body').css({'overflow':'hidden'});
		$.createEle('div', {id:'happyReader_getNextPageMask'}, {position:'absolute', width:'100%', height:document.body.scrollHeight+'px', zIndex:9999999, background:'#000', opacity:.8}).html('<p style="margin:300px 0 0;font-size:40px;color: white;text-align:center;">Don\'t Closed</p>').appendTo($('body'));
	} 
});
connection.postMessage({"action":"getOptions"});
connection.onMessage.addListener(function(msg,conn){
    setting_textSkin = msg.setting_textSkin;
	options_hotkey = msg.options_hotkey;
	options_enableAnalysisHelper = msg.options_enableAnalysisHelper;
	options_enableSuperAutoNextPage = msg.options_enableSuperAutoNextPage;
	if (options_enableAnalysisHelper === ''){
	   options_enableAnalysisHelper = 1;
	   conn.postMessage({action:"setOptionsEnableAnalysisHelper", "value":options_enableAnalysisHelper});
	}
	if (options_enableSuperAutoNextPage === ''){
       options_enableSuperAutoNextPage = 1;
       conn.postMessage({action:"setOptionsEnableSuperAutoNextPage", "value":options_enableSuperAutoNextPage});
    }
});

document.addEventListener('keydown', function(e){
	if (options_hotkey && options_hotkey.enable){
		var map = {ctrl:'ctrlKey', alt:'altKey', shift:'shiftKey'}, funcKeys=[];
		['image', 'text'].forEach(function(item){
			var res = false;
			options_hotkey[item].split('+').forEach(function(hotkey){
				var key = hotkey.toLowerCase();
				if (map[key]){
					funcKeys.push(map[key]);
                }else if(e.keyCode == key.charCodeAt() || e.keyCode == key.toUpperCase().charCodeAt()){
					res = true;
					funcKeys.forEach(function(funcKey){
                        res = res && e[funcKey];
                    });
				}
				
				if (res){
					guard.userRun = true;
					guard.userViewMode = item;
                    guard.docReady ? guard.run() : guard.showTip();
					_gaq.push(['_trackEvent', 'callExtMode::hotKey', 'callExtMode']);
				}
			});
		})
	}
}, false);

var guardHandle  = setInterval(function(){
	if (['complete', 'interactive'].indexOf(document.readyState)>-1){
	   guard.ready();
	   clearInterval(guardHandle);
       guardHandle = null;
	   
	   if (isTabForNextPage){
            happyReader.getNextPageUrl();
			var nextContent = happyReaderText.getData(),
			    connect = chrome.extension.connect();
			connect.postMessage({action:"setNextPageContent", url:happyReader.nextPageUrl, content:nextContent});
			happyReader.nextPageUrl ? location.href = happyReader.nextPageUrl : connect.postMessage({action:"noNextPageContent"});
			return ;
	   }
	   
	   try{
		   if (!options_enableAnalysisHelper) {
                return;
		   }
		   
		   happyReader.getData();
		   
		   if (!happyReaderImg.checkModeValid() && !happyReaderText.checkModeValid()) {
                return;
		   }
		   guard.createPet();
		   guard._begin = +new Date();
		   guard.refreshImg();
	   }catch(e){}
	}
}, 200);

window.addEventListener('load', function(){
	guard.clearRefreshImgHandle();
});

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (guard.userRun && guard.docReady){
		return;
	}
	
	guard.userRun = true;
	guard.docReady ? guard.run() : guard.showTip();
	_gaq.push(['_trackEvent', 'callExtMode::'+request.callExtMode, 'callExtMode']);
    sendResponse({});
});

//use super next page
chrome.extension.onConnect.addListener(function(port){
	port.onMessage.addListener(function(msg,conn){
		if (options_enableSuperAutoNextPage) {
			if (msg.action == 'setNextPageContent') {
				happyReader.curPage++;
				$.removeEle($('#textCanvas_loading'));
				$.createEle('article').css({background: happyReaderText.getTextSkinBg(),width:happyReaderText.getArticlePageWidth(happyReaderText.getTextPageWidth())}).html("<page>" + happyReader.curPage + "/<totalPage>1</totalPage></page>" + (msg.content || "<p>" + _m("noText") + "</p>")).appendTo($('#textCanvas'));
				$.createEle('div', {id: 'textCanvas_loading'}).html('Loading .... ').appendTo($('#textCanvas'));
				happyReaderText.updateFontSize(happyReaderText.getFontSize());
				
				var totalPages = document.getElementsByTagName('totalPage');
				for (var i = 0, totalPage; totalPage = totalPages[i++];) {
					totalPage.innerHTML = happyReader.curPage;
				};
			}else if (msg.action == 'noNextPageContent') {
				$.removeEle($('#textCanvas_loading'));
			}
		}
		
		if (msg.action == 'updateTextSkin'){
			for(var k in msg.textSkin){
				if (setting_textSkin[k] != msg.textSkin[k]){
                    if (k == 'bg'){
                        happyReaderText.updateTextSkinBg(msg.textSkin.bg);
                    }else if (k == 'fontSize') {
						happyReaderText.updateFontSize(msg.textSkin.fontSize);
					}else if (k == 'pageWidth') {
						happyReaderText.resetTextPageWidthValue(msg.textSkin.pageWidth);
					}
                }
			}
			setting_textSkin = msg.textSkin;
		}
	});
});
